package controllers;

import java.util.List;

import models.ArcadiaLog;
import models.Organizacion;

import controllers.CRUD.ObjectType;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import play.mvc.With;
import utils.ArcadiaConstants.TIPO_ENTIDAD;
import utils.DateHelper;

@With(Secure.class)
public class ArcadiaLogs extends ArcadiaCRUD {

	public static void list(Long idEntidad, String entidadName, int page, String search, String searchFields, String orderBy, String order) {
		ObjectType type = ObjectType.get(getControllerClass());
		notFoundIfNull(type);
		if (page < 1) {
			page = 1;
		} 

		String usuario = "";
		String desde = "";
		String hasta = "";		
		String where = "";
		
		 
		if (idEntidad==null && params.get("idEntidad")!=null) {
			idEntidad = new Long(params.get("idEntidad").toString()); 
		}
		if (!"".equals(idEntidad)){
			where = "idEntidad = ";
			where = where.concat(idEntidad.toString());			
		}
	
		if ((entidadName==null || "".equals(entidadName.trim())) && params.get("entidadName")!=null) {
			entidadName = params.get("entidadName").toString();
		} 
		
		if (searchFields != null && !"".equals(searchFields.trim())) {
			String[] filtros = searchFields.split(",");
			desde = filtros[0].trim().toUpperCase();
	    	hasta = filtros[1].trim().toUpperCase();

			if (desde!=null && !"".equals(desde)){
				if (!"".equals(where.trim()))
					where = where.concat(" and ");
		    	where = where.concat("fecha >= '");
		    	where = where.concat(desde);		  
		    	where = where.concat("'");
	    		
	    	}
	    	if (hasta!=null && !"".equals(hasta)){
	    		if (!"".equals(where.trim()))
					where = where.concat(" and ");
		    	where = where.concat("fecha <= '");
		    	where = where.concat(hasta);		  
		    	where = where.concat("'");
	    	}  
				
		}
		
		if (search!=null && !"".equals(search)){
			if (!"".equals(where.trim()))
				where = where.concat(" and ");
			usuario = search.trim();
			where = where.concat(" user.username like '%");
			where = where.concat(usuario);
			where = where.concat("%'");
		}
		
		if ("".equals(where.trim()))
			where = null;

		search = null;
		searchFields = null;
		
		if ("Usuario".equals(orderBy)){
			orderBy = "user";
		}
		List<Model> objects = type.findPage(page, search, searchFields, orderBy, order, where);
		Long count = type.count(search, searchFields, where);
		Long totalCount = type.count(null, null, where);
		
		try {
			render(type, objects, count, totalCount, page, orderBy, order, idEntidad, desde, hasta, usuario, entidadName);
		} catch (TemplateNotFoundException e) {
			render("CRUD/list.html", type, objects, count, totalCount, page, orderBy, order, idEntidad, desde, hasta, usuario, entidadName);
		}
	}
	
	//TODO: ORDENAR LOS LOGS EL MAS NUEVO PRIMERO
	
}
